import {celebrate, Joi} from "celebrate";
import {Request} from "express";
import * as express from "express";
import {RechargeModel} from "../database/models/recharge";
import {InternalError} from "./error";
import {withRecharge, Response} from "./middlewareType";
import {jwtAuthMiddleware} from "./passort";

const router = express.Router()

router.get('/',
  jwtAuthMiddleware,
  async (req: Request & withRecharge, res: Response) => {
    try {
      const recharge = await RechargeModel.find({state: 'on'})
        .lean()

      res.json({ok: true, data: {recharge}})
    } catch (e) {
      res.error(e)
    }
  })

router.get('/:rechargeId',
  celebrate({
    params: Joi.object({
      rechargeId: Joi.string().required()
    })
  }),
  async (req, res: Response) => {
    try {
      const recharge = await RechargeModel.findOne({_id: req.params.rechargeId})
        .lean()

      if (!recharge)
        throw InternalError('NO_SUCH_RECHARGE')

      res.json({ok: true, data: {recharge}})
    } catch (e) {
      res.error(e)
    }
  })

export default router
